package com.lxq.market.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lxq.market.model.App;
import com.lxq.market.model.User;
import com.lxq.market.service.AppService;
import com.lxq.market.service.CategoryService;
import com.lxq.market.util.SessionSignIn;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = {"/index",""})
public class IndexServlet extends HttpServlet {
	
	CategoryService categoryService=CategoryService.getInstance();
    SessionSignIn sign=SessionSignIn.getInstance();
    AppService appService=AppService.getInstance();
	
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user=sign.find(req.getSession().getId());
    	List<String> categories=categoryService.getCategoryName();
    	req.setAttribute("category", categories);

        appFilterStrategy(req);

        boolean signed = sign.signed(req.getSession().getId());
        if (signed){
            req.setAttribute("admin",user.getUserPosition().equals("站长")?1:0);
            req.setAttribute("user_entrance",user);
        }else{
            req.setAttribute("user_entrance",null);
        }
        req.getRequestDispatcher("/WEB-INF/index.jsp").forward(req,resp);
    }

    private void appFilterStrategy(HttpServletRequest req){
        String category=req.getParameter("app_category");
        String search=req.getParameter("search_app");
        if (search!=null){
            appNameStrategy(req,search.trim());
        }else if (category!=null){
            appCategoryStrategy(req,category.trim());
        }else{
            req.setAttribute("appList",appService.FindAllByStatueFilter());
            req.setAttribute("current_category","全部");
        }

    }
    private void appCategoryStrategy(HttpServletRequest req,String param){
        if (param.equals("全部")||param.equals("")){
            req.setAttribute("appList",appService.FindAllByStatueFilter());
            req.setAttribute("current_category","全部");
        }else{
            req.setAttribute("appList",appService.findAllByCategory(param));
            req.setAttribute("current_category",param);
        }
    }
    private void appNameStrategy(HttpServletRequest req,String param){
        if (param.equals("")){
            req.setAttribute("appList",appService.FindAllByStatueFilter());
            req.setAttribute("current_category","全部");
        }else{
            List<App> appList=new ArrayList<>();
            appList.add(appService.findByAppName(param));
            req.setAttribute("appList",appList);
            req.setAttribute("current_category","全部");
        }
    }

}
